package com.zooltech.samples.servlet3;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 访问压缩文件中的资源。
 * <br>/dochtml/路径下所有访问导向压缩文件。
 * 例子压缩文件中的是index.html及其相关资源。
 * 
 * @author zooltech@gmail.com
 *
 */
@WebServlet(urlPatterns={"/dochtml/*"},asyncSupported=true)
public class WebResource extends HttpServlet {

	/**
	 * 序列号.
	 */
	private static final long serialVersionUID = -5762321433882548445L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public WebResource() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	/**
	 * @param request request
	 * @param response response
	 * @throws ServletException ServletException
	 * @throws IOException IOException
	 */
	private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//		String path = request.getRequestURI();
//		int pos = path.indexOf(URL_STR);
//		path = path.substring(pos+URL_STR.length());

		//request.getPathInfo()返回相对于请求的serlvet的url的路径.即 http://localhost:8080/zip/dochtml后的路径
		String path = request.getPathInfo().substring(1);
		//如果tomcat配置不加URIEncoding="UTF-8",默认请求的编码是ISO-8859-1,所以转换成UTF-8,解决中文乱码。
		//path = new String(path.getBytes("ISO8859-1"),"UTF-8");

		System.out.println("path======> "+ path);
		InputStream is = getResource(new FileInputStream(this.getClass().getClassLoader().getResource("").getFile()+"test.zip"), path);
		OutputStream out = response.getOutputStream();
		int b;
		while ((b = is.read()) != -1)
			out.write(b);
		out.flush();
        out.close();
        is.close();
	}

	/**
	 * @param zipFileStream zip文件流
	 * @param resourceName 资源名成
	 * @return 资源对应的流
	 */
	private InputStream getResource(InputStream zipFileStream, String resourceName){
		ZipInputStream in = new ZipInputStream(zipFileStream);
		ZipEntry z;
		try {
			while ((z = in.getNextEntry())!=null) {
				if(z.getName().equals(resourceName)){
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return in;
	}
}
